import { ComponentInfoType, ComponentsStateType } from ".";

/**
 * 获取下一个 selectedId
 * @param fe_id 当前的ID
 * @param componentList 组件列表
 */
export function getNextSelectedId(
  fe_id: string,
  componentList: ComponentInfoType[]
) {
  const visibleComponentList = componentList.filter(
    (component) => !component.isHidden
  );
  const index = visibleComponentList.findIndex(
    (component) => component.fe_id === fe_id
  );

  if (index < 0) return "";
  //重新计算selectedId
  let newSelectedId = "";
  const length = visibleComponentList.length;
  if (length <= 1) {
    //组件长度就一个，被删除了，就没有组件
    newSelectedId = "";
  } else {
    if (index + 1 === length) {
      //要删除最后一个
      newSelectedId = visibleComponentList[index - 1].fe_id;
    } else {
      //删除的不是最后一个，删除后要选中下一个
      newSelectedId = visibleComponentList[index + 1].fe_id;
    }
  }
  return newSelectedId;
}

/**
 *
 * @param draft state draft
 * @param newComponent 新组件
 */
export function insertNewComponent(
  draft: ComponentsStateType,
  newComponent: ComponentInfoType
) {
  //解析出当前是否有选中的组件
  const { selectedId, componentList } = draft;
  const index = componentList.findIndex(
    (component) => component.fe_id === selectedId
  );
  //根据是否选择的组件添加的位置不同
  if (index < 0) {
    //未选择
    draft.componentList.push(newComponent);
  } else {
    //选中组件
    draft.componentList.splice(index + 1, 0, newComponent);
  }

  draft.selectedId = newComponent.fe_id;
}
